<template>
  <!-- 项目新增/编辑表单 -->
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
    <el-form-item label="编码" prop="code">
      <el-input v-model="formData.code" placeholder="编码" />
    </el-form-item>
    <el-form-item label="名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入名称" />
    </el-form-item>

    <el-form-item label="类型" prop="type">
      <el-radio-group v-model="formData.type">
        <el-radio value="table">表</el-radio>
        <el-radio label="produce">存储过程</el-radio>
        <el-radio label="comm">常量</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="渲染内容" prop="content">
      <el-input v-model="formData.content" placeholder="渲染内容" />
    </el-form-item>
    <el-form-item label="渲染字段" prop="valueField">
      <el-input v-model="formData.valueField" placeholder="渲染内容" />
    </el-form-item>
    <el-form-item label="显示字段" prop="displayField">
      <el-input v-model="formData.displayField" placeholder="显示字段" />
    </el-form-item>
  </el-form>
</template>
<script setup>
  import { findById, saveData, list } from '@/api/system/renderConfig/index';

  const props = defineProps({ id: { type: String, required: true }, productId: { type: String, required: true } });

  let defaultFromData = {
    id: '',
    code: '',
    productId: props.productId,
    type: 'table',
    content: '',
    valueField: '',
    displayField: '',
  };

  const formData = reactive(Object.assign({}, defaultFromData));

  watch(
    () => props.id,
    () => {
      if (props.id) {
        loadData();
      } else {
        setValue({});
      }
    },
    { immediate: true }
  );

  function loadData() {
    findById(props.id).then(({ data }) => {
      setValue(data);
    });
  }

  // 校验规则
  const rules = reactive({
    name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
  });

  const formRef = ref(ElForm);

  function save() {
    formRef.value.validate((valid) => {
      if (valid) {
        saveData(formData, true).then(({ data }) => {
          formData.id = data.id;
          ElMessage.success('保存功能成功');
        });
      }
    });
  }

  function setValue(data) {
    Object.assign(formData, defaultFromData, data);
  }

  defineExpose({ save, setValue });
</script>
